import axios from 'axios'

const API_BASE_URL = "http://127.0.0.1:8000";

const service = axios.create({
    //url = base url + reqeust url
    baseURL : API_BASE_URL,
    
    //配置请求超时时间
    timeout: 5000
})

export default service

const decoder = new TextDecoder();

export const fetchStreamData = async (url, params, onData, onComplete) => {
    const targetUrl = new URL(API_BASE_URL + url);

    // 添加查询参数
    if (params) { // 此处判断会排除null和undefined的情况
        Object.keys(params).forEach(key => {
            targetUrl.searchParams.append(key, params[key]);
        });
    }

    const response = await fetch(targetUrl);
    const reader = response.body.getReader();

    const processText = async ({ done, value }) => {
        if (done) {
            onComplete(); // 调用流完成的回调
            return;
        }
        onData(decoder.decode(value, { stream: true })); // 处理接收到的数据块
        reader.read().then(processText); // 递归读取下一个数据块
    };

    reader.read().then(processText);
};
